<template>
    <div class="view page-gameAnswer">
        <div class="m-header">
            <div class="utitle">{{roomInfo.themeName}}</div>
            <div class="rowbox">
                <div class="leftbox">
                    <div class="avater">
                        <img :src="roomInfo.userAvatar?roomInfo.userAvatar:headError" :onerror="headError">
                    </div>
                    <div class="info">
                        <div class="name">{{roomInfo.name}}</div>
                        <div class="score"><span>{{wrongObj.score}}</span>分</div>
                    </div>
                    <div class="wrong">
                        <span v-for="(item,index) in wrongObj.num" :key="index" :class="{'on': wrongObj.match > index}"></span>
                    </div>
                </div>
                <div class="rightbox">
                    <div class="avater">
                        <img :src="roomInfo.self_userAvatar?roomInfo.self_userAvatar:headError" :onerror="headError">
                    </div>
                    <div class="info">
                        <div class="name">{{roomInfo.self_name}}</div>
                        <div class="score"><span>{{wrongObj.self_score}}</span>分</div>
                    </div>
                    <div class="wrong">
                        <span v-for="(item,index) in wrongObj.num" :key="index" :class="{'on': wrongObj.self > index}"></span>
                    </div>
                </div>
            </div>
        </div>
        <!-- roomInfo.num 先手后手 -->
        <div :class="['m-con',{'before':roomInfo.num==1}]">
            <div class="answList clearfix" :class="{'self':item.status == 1}" v-for="(item,index) in answerList" :key="index">
                <div class="avater">
                    <img :src="item.userAvatar?item.userAvatar:headError" :onerror="headError" alt="">
                </div>
                <div :class="['vcon',{'wrong':!item.correct}]" v-html="answerFilters(item)"></div>
            </div>
        </div>
        <div class="m-footer" v-if="!drawRes&&!canvasShow&&vloading&&!isEnd">
            <div class="vtips">等待对手作答...</div>
            <div class="timer">
                <span>{{time | timeCount}}</span>
            </div>
        </div>
        <div class="mask" v-if="mask"></div>
        <div :class="['layerCan',{'drawCan':drawRes,'endCan':isEnd}]" v-show="canvasShow">
            <canvas id="can"></canvas>
            <div v-if="actDraw" class="drawbtn" @click="clickDraw()"></div>
            <div class="endCan_box" :class="'endResImg'+endRes" v-if="isEnd">
                <div class="resLi self">
                    <div class="avater">
                        <img :src="roomInfo.self_userAvatar?roomInfo.self_userAvatar:headError" :onerror="headError">
                    </div>
                    <div class="vinfo">
                        <div class="name">{{roomInfo.self_name}}</div>
                        <div class="totil">答对：{{wrongObj.selfTotil-wrongObj.self}}句</div>
                    </div>
                    <div class="score"><span>{{wrongObj.self_score}}</span>分</div>
                </div>
                <div class="resLi match">
                    <div class="avater">
                        <img :src="roomInfo.userAvatar?roomInfo.userAvatar:headError" :onerror="headError">
                    </div>
                    <div class="vinfo">
                        <div class="name">{{roomInfo.name}}</div>
                        <div class="totil">答对：{{wrongObj.matchTotil-wrongObj.match}}句</div>
                    </div>
                    <div class="score"><span>{{wrongObj.score}}</span>分</div>
                </div>
                <div class="btnBox">
                    <div class="u-btn border" @click="clickAgain">再来一次</div>
                    <div class="u-btn btnbg" @click="$router.push({path:'/game'})">返回首页</div>
                </div>
            </div>
        </div>
        <!-- 判断答题对错 -->
        <div class="anslayer" :class="'ansTips'+ansState" v-if="ansState!=0"></div>

        <Layer :class="{'empty': !ansValue||!ansValue.length}" :visible="!drawRes&&!canvasShow&&!vloading&&!isEnd" @change="changeLayer" cancel="提交答案"> 
            <div class="timer" slot="icon"><span>{{time | timeCount}}</span></div>
            <h3 slot="title">飞花令主题：{{roomInfo.themeName}}</h3>
            <div class="ansCon">
                <input v-model="ansValue" type="text" placeholder="请输入你的答案...">
            </div>
            <p class="u-tips" slot="tips">提示：请注意标点符号和诗句完整性哦~</p>
        </Layer>
    </div>
</template>
<script>
import * as api from '@/api/index';
import UPlayAnimate from './imgCanvas'
export default {
    data(){
        return {
            headError: this.$store.state.headError,
            userId: this.$store.state.userId,
            userInfo: JSON.parse(localStorage.getItem("userInfo")),
            
            roomInfo: this.$store.state.roomInfo,       //房间信息
            socket: this.$store.state.socket,           //获取socket对象
            aid:'001',
            uid: this.$store.state.uid,
            robotMsgList:[],                //机器人的答题信息
            curInd: 0,                      //当前第几题
            
            initTime: 90,                   //默认等待倒计时1分钟
            time: 0,                        
            timeLoop: null,                 //倒计时容器
            timeRobot: null,                //倒计时容器(机器人答题)

            canvasShow: false,             //是否展示canvas
            handleNew: null,                //构造的逐帧动画

            drawRes: true,                 //抽签弹层
            actDraw: true,                 //是否有抽签操作区
            is_clickDraw: false,             //是否点击抽签按钮

            vloading: false,                 //等待答题倒计时
            ansValue: '',                   //答题  
            ansState: 0,                //答题状态 0消失   1正确   2错误
            answerList:[],
            wrongObj:{           
                num: 3,
                selfTotil:0,           
                self:0,
                self_score:0,
                matchTotil: 0,
                match:0,
                score:0,
            },
            isEnd: false,                   //是否答题结束
            endRes: 1,                      //1 成功  2 失败
            issocket_msg: 0,             //防止动画还未结束 先收到信息造成误差冲突   1----自己    2-----对手

            mask: false,       
            isLeave_match: false,           //对手是否离开房间   兼容返回重复回调     
            isGoBack: false,                //是否按返回键退出房间

            disabled: false,                //防止重复提交
        }
    },
    filters:{
        timeCount(value){
            value = (value<10)?'0'+value:value;
            return value
        },
    },
    mounted(){
        if (window.history && window.history.pushState) {
            history.pushState(null, null, document.URL);
            window.addEventListener('popstate', this.goBack, false);
        }
        document.addEventListener('visibilitychange',this.diffTime)
        this.getInit()
    },
    methods:{
        goBack(){
            clearInterval(this.timeLoop)
            window.removeEventListener('popstate', this.goBack, false);
            this.$router.push({path:'/game'})
            this.isGoBack = true
            this.disconnect()
        },
        diffTime(){
            if (document.visibilityState =='hidden') {
                clearInterval(this.timeLoop)
                this.$router.push({path:'/game'})
                this.disconnect()
                document.removeEventListener('visibilitychange', this.diffTime);
            } 
        },
        /********
         * 初始化  抽签弹层默认显示
         * vloading: true 答题等待 false: 开始答题    
         * canvasShow 控制显示canvas   drawRes控制显示的是抽签canvas
         * roomInfo: 房间基础信息 
         * num: 抽签结果 1先手   0后手
         * server_response —— msgType： 1 加入房间  2 房间信息   3 有人退出房间   4 有人退出房间
         * isRobot 是否是机器人 1:是  0:不是
         * levelModel  答题难度  1星答题时间90s 二星90s  三星60秒  四星45秒  五星30秒
         * **********/ 
        getInit(){
            // 防止页面手动刷新
            if(!this.roomInfo || JSON.stringify(this.roomInfo) == '{}'){
                this.$router.push({path:'/game'})
                return false
            }
            
            this.canvasShow = this.drawRes = this.mask = true
            var can = document.getElementById('can');
            can.width = 678;
            can.height= 828;
            var sources = [];
            var drawUrl = this.roomInfo.num == 1?'before':'after'
            //构建图片序列数据
            for(var i=0;i<7;i++){
                sources[i] = "./static/img/draw/" + (10000+i+1) + ".png";//根据项目修改
            }
            for(var i=7;i<23;i++){
                sources[i] = "./static/img/draw/"+drawUrl+"/" + (10000+i+1) + ".png";//根据项目修改
            }
            var dataSetting = {
                sources: sources,
                stepAct: false,
                step:{val: 15, time: 1500}
            }
            this.handleNew = new UPlayAnimate(can,dataSetting)

            let levelModel = sessionStorage.getItem('levelModel')  
            levelModel == 3 && (this.initTime = 60)
            levelModel == 4 && (this.initTime = 45)
            levelModel == 5 && (this.initTime = 30)

            // 若超过5秒未点击抽签则自动抽签
            this.time = 5
            this.countTime()

            // 若匹配机器人，获取机器人的答题信息
            if(this.roomInfo.isRobot == 1){
                this.getRobotMsgList()
            }


            this.vloading = this.roomInfo.num == 1?false:true
            //  服务端消息接收接口
            this.socket && this.socket.on('server_response', (msg, cb) => {
                const { msgType,data} = msg     
                console.log(msg)
                if(msgType==2){        //房间内部发送信息
                    this.disabled = false
                    this.canvasShow = this.drawRes = false
                    clearInterval(this.timeLoop)
                    var info = data?JSON.parse(data):{}
                    if(this.vloading){                      //vloading: true 答题等待 false: 开始答题  
                        this.curInd++
                    }
                    if(info.userId == this.userId){         //判断该条信息是谁发送
                        this.issocket_msg = 1
                        info.userAvatar = this.roomInfo.self_userAvatar
                        info.name = this.roomInfo.self_name
                        info.status = 1             //是否是自己 1是 0 不是
                        this.wrongObj.selfTotil++
                        if(!info.correct) this.wrongObj.self++
                        else this.wrongObj.self_score = (this.wrongObj.selfTotil-this.wrongObj.self) *10
                        this.getAnsState(info.correct)    //correct判断是否是正确的
                    }else{
                        this.issocket_msg = 2
                        info.userAvatar = this.roomInfo.userAvatar
                        info.name = this.roomInfo.name
                        info.status = 0
                        this.wrongObj.matchTotil++
                        if(!info.correct) this.wrongObj.match++
                        else this.wrongObj.score = (this.wrongObj.matchTotil-this.wrongObj.match) *10
                        if(this.wrongObj.match<3){
                            setTimeout(()=>{
                                this.mask = true
                                this.vloading = false
                                this.time = this.initTime
                                this.countTime()
                            },1400)
                        }else{
                            this.endAnswer('match')
                        }
                    }
                    this.answerList.push(info)

                    
                }else if((msgType == 3||msgType == 4) && !this.isLeave_match){
                    if(this.wrongObj.match<3 && this.wrongObj.self<3){
                        this.isLeave_match = true
                        this.$LayerTips({
                            content: "对方已经退出游戏",
                            time: 1500
                        });  
                        clearInterval(this.timeLoop)
                        setTimeout(()=>{
                            this.endAnswer('match')
                        },1500)
                    }
                }     
                if (cb) cb();      
            });
            // 自己断网等情况...
            this.socket && this.socket.on('connect_error', () => {
                console.log('断开连接(断网) :' ,event)
            })
            this.socket && this.socket.on('disconnect', ()=> {
                if(this.wrongObj.match<3 && this.wrongObj.self<3 && !this.isLeave_match){
                    if(this.isGoBack){
                        this.$LayerTips({
                            content: "您已退出游戏",
                            time: 1500
                        });  
                        clearInterval(this.timeLoop)
                    }else{
                        this.$LayerTips({
                            content: "有网络波动，您已断开连接",
                            time: 1500
                        });  
                        clearInterval(this.timeLoop)
                        this.$router.push({path:'/game'})
                    }
                }
                console.log('断开连接 :' ,event)
            })
        },
        /****
         * 触发抽签
         * vloading: true 答题等待 false: 开始答题    
         * 若是先手则弹出答题弹层   若是后手则显示答题等待
         * type： 空是点击抽签按钮触发  'auto'是超时自动触发
        * ****/ 
        clickDraw(type){
            this.actDraw = false
            if(!type) this.is_clickDraw = true
            this.handleNew.switch((rafId)=>{
                this.mask = this.canvasShow = false
                if(type == 'auto' && this.issocket_msg == 0){
                    this.drawRes = false
                    this.mask = !this.vloading
                    this.time = this.initTime
                    this.countTime()
                }
            })
        },
        /****
         * 倒计时
        * ****/ 
        countTime(){
            this.timeLoop = setInterval(()=>{
                if(this.time>0){
                    this.time--
                    if(this.drawRes && !this.is_clickDraw && this.time==2){            //若超过5秒未点击抽签则自动抽签
                        clearInterval(this.timeLoop)
                        this.clickDraw('auto')
                    }
                    if(!this.drawRes && this.vloading && this.time==this.initTime-20){
                        this.RobotAnswer()

                    }
                    this.socket && this.socket.emit('client_ping_pong', this.time);
                } else {
                    clearInterval(this.timeLoop)
                    if(!this.drawRes&&!this.vloading){                  //答题倒计时结束 触发判断答题是否正确
                        var data = {
                            num: this.roomInfo.num,
                            roomId: this.roomInfo.roomId,
                            userId: this.userId,
                            content: "",        
                            isCorrect: false            
                        }
                        this.sendSocket(JSON.stringify(data))
                    }
                    if(!this.drawRes&&this.vloading){                   //等待答题倒计时
                        this.mask = true
                        this.vloading = false
                        this.time = this.initTime
                        this.countTime()
                    }
                    if(this.drawRes){                           //点击抽签按钮之后为保证双方开始答题时间一致，控制打开页面5s之后再开始倒计时答题
                        this.drawRes = false    
                        this.mask = !this.vloading
                        this.time = this.initTime
                        this.countTime()
                    }
                }
            },1000)
        },
        changeLayer(){
            if(this.ansValue&&this.ansValue.length&&!this.disabled){
                var data = {
                    num: this.roomInfo.num,
                    roomId: this.roomInfo.roomId,
                    userId: this.userId,
                    content: this.ansValue,        
                    isCorrect: false            
                }
                this.disabled = true
                this.sendSocket(JSON.stringify(data))
            }
        },
        // 答题的对错提示
        getAnsState(correct){
            this.vloading = true
            this.mask = false
            this.ansValue = ""
            this.ansState = correct?1:2
            setTimeout(()=>{
                this.ansState = 0
                if(this.issocket_msg == 1){
                    if(this.wrongObj.self < 3){
                        this.vloading = true
                        this.time = this.initTime
                        this.countTime()
                    }else{
                        this.endAnswer('self')
                    }
                }
            },1500)
        },
        /*********
         * 答题结束
         * type=='self'?'失败':'成功'
         * *********/ 
        async endAnswer(type){
            var can = document.getElementById('can');
            can.width = 602;
            can.height= 968;
            var sources = [];

            var endUrl = type=='self'?'error':'success'
            this.endRes = type=='self'?2:1
            //构建图片序列数据
            for(var i=0;i<8;i++){
                sources[i] = "./static/img/endRes/"+endUrl+"/" + (10001+i) + ".png";//根据项目修改
            }
            var data = {
                futureId: this.userInfo.futureId ,
                roomId: this.roomInfo.roomId
            }
            var res = await api.createRoomResult(data)
            if(res.resultCode == 1){
                this.canvasShow = this.isEnd = true
                this.mask = true
                var dataSetting = {
                    sources: sources,
                    stepAct: true,
                    diffTimestep: 100
                }
                this.handleNew.reset(dataSetting,()=>{
                })
            }
            console.log('答题结束',type=='self'?'失败':'成功')
            
            this.disconnect()
        },
        // 机器人答题
        async getRobotMsgList(){
            var data = {
                themeId: this.roomInfo.themeId
            }
            var res = await api.getRobotMsgList(data)
            if(res.resultCode == 1){
                this.robotMsgList = res.value?res.value:[]
            }
        },
        RobotAnswer(){
            // 若匹配机器人
            if(this.roomInfo.isRobot == 1){
                var len = this.robotMsgList.length
                var data = {
                    num: this.roomInfo.num==1?0:1,
                    roomId: this.roomInfo.roomId,
                    userId: this.roomInfo.robotId,
                    content: (this.curInd+1)<len?this.robotMsgList[this.curInd]:'',        
                    isCorrect: false            
                }
                this.sendSocket(JSON.stringify(data))
            }
        },

        sendSocket(data){
            var sendData = {
                ...this.prepareSendData(data),
                room: this.roomInfo.roomId
            }
            this.socket && this.socket.emit('client_send_room_message', sendData);
        },
        prepareSendData(text){
            return {
                aid : this.aid,
                uid: this.uid,
                data: text
            }
        },
        clickAgain(){
            this.$router.push({path:'/gameMatch',query:{themeId:this.roomInfo.themeId}})
        },
        // 断开连接
        disconnect(){
            if(this.socket){
                var data = this.prepareSendData('')
                this.socket.emit('leave',{'room':this.roomInfo.roomId,...data});
                this.socket.emit('disconnect_request', data);
                this.socket = null
                this.$store.dispatch('DisSocketConnect')
            }
        },
        
        answerFilters(item){
            if(item.correct){             //正确
                var reg=new RegExp('\\'+this.roomInfo.themeName,'g');//声明一个正则表达式，为了将所有的行的关键字都加红
                return item.content.replace(reg,'<b style="color:red">'+this.roomInfo.themeName+'</b>');//将关键字替换成加粗的关键字
            }else{
                return (item.userId == this.userId?'您':item.name) +'的回答错误...'
            }
        }
    },
    destroyed(){
        this.disconnect()
        clearInterval(this.timeLoop)
        this.handleNew = null
        this.timeLoop = null
    }
}
</script>